package com.briup.appointment.common;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice(basePackages = "com.briup.appointment.controller")
public class GlobalExceptionHandler {

    @ExceptionHandler({MethodArgumentNotValidException.class, BindException.class, HttpMessageNotReadableException.class})
    public ApiResponse<Void> handleBadRequest(Exception e, HttpServletRequest request) throws Exception {
        String uri = request != null ? request.getRequestURI() : null;
        if (uri != null && (uri.startsWith("/v3/api-docs") || uri.startsWith("/swagger-ui") || uri.startsWith("/swagger") || uri.startsWith("/webjars"))) {
            throw e;
        }
        return ApiResponse.fail(e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public ApiResponse<Void> handleOther(Exception e, HttpServletRequest request) throws Exception {
        String uri = request != null ? request.getRequestURI() : null;
        if (uri != null && (uri.startsWith("/v3/api-docs") || uri.startsWith("/swagger-ui") || uri.startsWith("/swagger") || uri.startsWith("/webjars"))) {
            throw e;
        }
        return ApiResponse.fail(e.getMessage());
    }
}


